<div class="ui segments" id="{{$elId}}" v-cloak>
    <div class="ui segment secondary clearing">
        <span class="ui header" v-text="title ? title : (id?`编辑 ${resource}`:`创建 ${resource}`)"></span>
        <div class="ui icon buttons right floated">
            <a :href="`/admin/${resource}`" class="ui button small teal" title="列表">
                <i class="icon list"></i>
            </a>
            <a v-if="formType=='edit'" :href="`/admin/${resource}/${id}`" class="ui button small blue" title="详情">
                <i class="icon file outline"></i>
            </a>
            <a v-if="formType=='edit'" @click.prevent="handleDelete" class="ui button small red" title="删除">
                <i class="icon trash alternate outline"></i>
            </a>
        </div>
        
    </div>
    <div class="ui segment clearing">
        <form class="ui form">
            <div v-for="(field, index) in fields" class="field" :class="{inline: field.type==='pk'}" v-if="!(formType=='create' && field.type === 'pk')">
                <label v-text="field.label"></label>
                <template v-if="field.type=='pk'">
                    <input type="number" disabled :value="values[index]">
                </template>
                <template v-else-if="field.type=='select' && field.options">
                    <select v-model="values[index]">
                        <option v-for="v, k in field.options" :value="k" v-text="v"></option>
                    </select>
                </template>
                <template v-else-if="field.type=='image'">
                    <input v-model="values[index]" type="text" :disabled="field.disabled || !field.isPure">
                    <image :src="values[index]" v-if="_.startsWith(values[index], 'http')" class="ui bordered image" :class="field.formSize">
                </template>
                <template v-else-if="field.type=='html'">
                    <quill-editor v-model="values[index]" :disabled="field.disabled || !field.isPure"></quill-editor>
                </template>
                <template v-else-if="field.type=='number'">
                    <input v-model.number="values[index]" type="number" :disabled="field.disabled || !field.type || !field.isPure">
                </template>
                <template v-else>
                    <input v-model="values[index]" type="text" :disabled="field.disabled || !field.type || !field.isPure">
                </template>
            </div>
            <div class="field">
                <div class="ui buttons right floated">
                    <button @click.prevent="handleReset" class="ui button small">重置</button>
                    <button @click.prevent="handleSubmit" class="ui button small blue">提交</button>
                </div>
            </div>
        </form>
    </div>
    <div class="ui segment">
        <div ref="jsonView"></div>
    </div>
</div>

@push('js')
<script>
/**
 * {{$elId}}
 */
$(function(){
    const elId = {!! json_encode($elId) !!}
    const vueData = {
        title: {!! json_encode($title) !!},
        actions: {!! json_encode($actions) !!},
        resource: {!! json_encode($resource) !!},
        id: {!! json_encode($id) !!},
        fields: {!! json_encode($fields) !!},
        values: {!! json_encode($values) !!},
        originValues: {!! json_encode($values) !!},
        payload: {!! json_encode($payload) !!},
    }
    new Vue({
        el: '#' + elId,
        data: vueData,
        methods: {
            handleReset(){
                this.values = [...this.originValues]
            },
            handleSubmit(){
                const params = _.assign(this.changedValues, this.payload);

                if (this.formType == 'edit') {
                    axios.put(`/admin/${this.resource}/${this.id}`, params)
                    .then(() => {
                        toastr.info(`更新成功`)
                        this.originValues = [...this.values]

                        delayRedirect(`/admin/${this.resource}/${this.id}`)
                    }).catch(error => {
                        console.error(error)
                        toastr.error(`更新失败：${error}`)
                    })
                } else {
                    axios.post(`/admin/${this.resource}`, params)
                    .then(({data}) => {
                        toastr.info(`创建成功`)

                        delayRedirect(`/admin/${this.resource}/${data.id}`)
                    }).catch(error => {
                        console.error(error)
                        toastr.error(`创建失败：${error}`)
                    })
                }
            },
            handleDelete(){
                swal(`确定要删除记录 id=${this.id} 吗 ？`, {
                    dangerMode: true,
                    buttons: true,
                }).then((confirm) => {
                    if (!confirm) {
                        return;
                    }

                    axios.delete(`/admin/${this.resource}/${this.id}`)
                    .then(()=>{
                        toastr.info(`删除成功, id: ${this.id}`)

                        delayRedirect(`/admin/${this.resource}`)
                    }).catch(error => {
                        console.error(error)
                        toastr.error(`删除失败: ${error}`)
                    })
                })
            }
        },
        watch: {
            changedValues(values) {
                $(this.$refs.jsonView).JSONView(values)
            }
        },
        computed: {
            formType() {
                if (this.id) {
                    return 'edit'
                } else {
                    return 'create'
                }
            },
            changedValues() {
                let rv = {};
                _.forEach(this.fields, (field, index) => {
                    const oriValue = this.originValues[index]
                    let value = this.values[index]
                    if (_.isString(value)) {
                        value = value.trim()
                    }

                    if (_.isUndefined(oriValue)) {
                        if (!value) {
                            return
                        }
                    }
                    if (oriValue !== value) {
                        rv[field.name] = value
                    }
                })
                return rv;
            }
        },
    })
})
</script>
@endpush